<!-- src/components/LineChart.vue -->
<template>
  <div>
    <div ref="chart" style="width: 100%; height: 400px;"></div>
    <el-button type="primary" @click="downloadData" style="margin-top: 20px;">下载数据</el-button>
  </div>
</template>

<script>
import * as echarts from 'echarts';

export default {
  props: {
    x: {
      type: Array,
      required: true
    },
    y: {
      type: Array,
      required: true
    },
    fileName: {
      type: String,
      required: false,
      default: '数据显示'
    }
  },
  mounted() {
    this.drawChart();
  },
  watch: {
    x() {
      this.drawChart();
    },
    y() {
      this.drawChart();
    }
  },
  methods: {
    drawChart() {
      const chart = echarts.init(this.$refs.chart);
      const option = {
        title: {
          text: this.fileName
        },
        tooltip: {
          trigger: 'axis',
          axisPointer: {
            type: 'cross'
          }
        },
        xAxis: {
          type: 'category',
          data: this.x
        },
        yAxis: {
          type: 'value'
        },
        dataZoom: [
          {
            type: 'slider',
            start: 0,
            end: 100
          },
          {
            type: 'inside',
            start: 0,
            end: 100
          }
        ],
        series: [{
          data: this.y,
          type: 'line'
        }]
      };
      chart.setOption(option);
      this.chart = chart;
    },
    downloadData() {
      const date = new Date();
      const fileName = `${date.getFullYear()}-${(date.getMonth() + 1).toString().padStart(2, '0')}-${date.getDate().toString().padStart(2, '0')}_${date.getHours().toString().padStart(2, '0')}-${date.getMinutes().toString().padStart(2, '0')}-${date.getSeconds().toString().padStart(2, '0')}.txt`;

      const content = this.x.map((xValue, index) => `${xValue},${this.y[index]}`).join('\n');

      const blob = new Blob([content], { type: 'text/plain;charset=utf-8' });
      const link = document.createElement('a');
      link.href = URL.createObjectURL(blob);
      link.download = fileName;
      link.click();
      URL.revokeObjectURL(link.href);
    },
    beforeDestroy() {
      if (this.chart) {
        this.chart.dispose();
      }
    }
  }
};
</script>

<style scoped>
/* 添加必要的样式 */
</style>
